import request from "request"
import { requestPromise } from "../utils";
import get_acw_sc__v2 from "./acw_sc__v2";

export const getAcwSc = async (): Promise<string> => {
  const arg1 = await requestPromise('https://www.gigab2b.com/index.php?route=account/login', {
    gzip: true,
  }).then((response: request.Response): string => {
    const { body } = response;
    const bodyStr = typeof body === 'string' ? body : '';
    const regexp = /var arg1='([0-9A-Z]{40})'/;
    const matchResult = bodyStr.match(regexp);
    let arg1: null | string = null;
    if (matchResult !== null && matchResult.length === 2) {
      arg1 = matchResult[1];
    }
    if (arg1 === null) {
      throw new Error('arg1 匹配失败')
    }
    return arg1;
  })
  const acw_sc__v2 = get_acw_sc__v2(arg1)
  return acw_sc__v2;
}

export const getBasicInfo = async (): Promise<{
  acw_sc__v2: string;
  OCSESSID: string;
  'X-CSRF-TOKEN': string;
}> => {
  const acw_sc__v2 = await getAcwSc()

  let OCSESSID: string | undefined;
  let X_CSRF_TOKEN: string | undefined;

  const setOcSessId = (response: request.Response): void => {
    const cookieArray = response.headers["set-cookie"]?.filter(cookie => cookie.startsWith('OCSESSID'))
    if (cookieArray) {
      const [cookie] = cookieArray
      if (cookie) {
        const [keyValue] = cookie.split('; ');
        [, OCSESSID] = keyValue.split('=')
      }
    }
  }

  const setX_CSRF_TOKEN = (response: request.Response): void => {
    const regExp = /'X-CSRF-TOKEN', '([^']+?)'/;
    const matchArray = String(response.body).match(regExp)
    if (matchArray) {
      [, X_CSRF_TOKEN] = matchArray
    }
  }

  const response = await requestPromise('https://www.gigab2b.com/index.php?route=account/login', {
    gzip: true,
    headers: {
      Cookie: `acw_sc__v2=${acw_sc__v2}`
    }
  })
  setOcSessId(response)
  setX_CSRF_TOKEN(response)

  if (OCSESSID === undefined) {
    throw Error('OCSESSID is undefined')
  }
  if (X_CSRF_TOKEN === undefined) {
    throw Error('X-CSRF-TOKEN is undefined')
  }
  return {
    acw_sc__v2,
    OCSESSID,
    'X-CSRF-TOKEN': X_CSRF_TOKEN,
  }
}
